package com.suyang.syt.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suyang.syt.context.BeanFactoryContext;
import com.suyang.syt.dao.interfaces.UserDao;
import com.suyang.syt.dao.interfaces.WeixinQRcodeDao;
import com.suyang.syt.dao.interfaces.WeixinUserDao;
import com.suyang.syt.model.User;
import com.suyang.syt.model.WeixinQRcode;
import com.suyang.syt.model.WeixinUser;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.PagerEasyUI;
import com.suyang.syt.service.interfaces.WeixinQRcodeService;
import com.suyang.syt.util.DateFormat;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.util.Md5Util;
import com.suyang.syt.weixin.WeixinKit;
import com.suyang.syt.weixin.WeixinMessage;

@Service
public class WeixinQRcodeServiceImpl implements WeixinQRcodeService {
	@Autowired
	private WeixinQRcodeDao weixinQRcodeDao;
	@Autowired
	private WeixinUserDao weixinUserDao;
	@Autowired
	private UserDao userDao;

	@Override
	public PagerEasyUI<WeixinQRcode> listByEasyUI(int page, int rows, String sort, String order) throws Exception {
		StringBuilder hql = new StringBuilder(" from WeixinQRcode wg where 1=1 ");
		if (EmptyUtil.isNotEmpty(sort)) {
			hql.append(" order by wg.").append(sort);
		}
		if (EmptyUtil.isNotEmpty(order)) {
			hql.append(" ").append(order);
		}
		PagerEasyUI<WeixinQRcode> easyUIPager = new PagerEasyUI<WeixinQRcode>();
		List<WeixinQRcode> list = weixinQRcodeDao.findByEasyUI(hql.toString(), page, rows);
		if (EmptyUtil.isNotEmpty(list)) {
			easyUIPager.setRows(list);
			easyUIPager.setTotal((Long) weixinQRcodeDao.queryByHql(" select count(*) " + hql.substring(0, hql.indexOf("order by"))));
		}
		return easyUIPager;
	}

	@Override
	public AjaxObj add(WeixinQRcode weixinQRcode) throws Exception {
		if (EmptyUtil.isEmpty(weixinQRcode.getQrdata())) {
			return new AjaxObj(0, "二维码中携带的数据不能为空!");
		}
		if (addBuildWeixinQrcode(weixinQRcode)) {
			return new AjaxObj(1, "二维码创建成功!");
		} else {
			return new AjaxObj(0, "二维码创建失败!");
		}
	}

	@Override
	public AjaxObj addQrlogin() throws Exception {
		WeixinQRcode weixinQRcode = new WeixinQRcode("微信登陆", 0, 1);
		if (addBuildWeixinQrcode(weixinQRcode)) {
			return new AjaxObj(1, "二维码创建成功!", weixinQRcode);
		} else {
			return new AjaxObj(0, "二维码创建失败!");
		}
	}

	@Override
	public AjaxObj updateQrlogin(int scene_id) throws Exception {
		if (scene_id > 100000) {
			WeixinQRcode weixinQRcode = weixinQRcodeDao.loadByScene(String.valueOf(scene_id));
			if (weixinQRcode != null) {
				if (weixinQRcode.getTimestamp() + weixinQRcode.getExpire_seconds() * 1000 > System.currentTimeMillis()) {
					// 临时二维码没有超时
					WeixinUser weixinUser = weixinUserDao.loadByOpenid(weixinQRcode.getQrdata());
					if (weixinUser != null && weixinUser.getStatus() == 1) {
						User user = userDao.load(weixinUser.getUid());
						if (user != null) {
							weixinQRcodeDao.delete(weixinQRcode);
							return new AjaxObj(1, "微信登陆成功!", user);
						}
					}
				} else {
					return new AjaxObj(0, "您好,您扫描的二维码已经过期,请重新刷新页面进行扫码!");
				}
			}
		}
		return new AjaxObj(0, "登陆失败,请重新刷新页面进行扫码!");
	}

	@Override
	public AjaxObj addQrpasswd() throws Exception {
		WeixinQRcode weixinQRcode = new WeixinQRcode("微信改密", 0, 2);
		// weixinQRcode.setQrdata("http://sixuekeji.wicp.net/syt/web/passwd.html");
		weixinQRcode.setQrdata(BeanFactoryContext.getCtx() + "/web/passwd.html");
		if (addBuildWeixinQrcode(weixinQRcode)) {
			return new AjaxObj(1, "二维码创建成功!", weixinQRcode);
		} else {
			return new AjaxObj(0, "二维码创建失败!");
		}
	}

	/** 构建微信二维码对象,并在数据库中保存 */
	private boolean addBuildWeixinQrcode(WeixinQRcode weixinQRcode) {
		try {
			if (weixinQRcode.getType() == 0) {
				// 临时二维码,临时的二维码必须有一个32位不重复的非0整型为场景值ID
				weixinQRcode.setScene_id(buildRandomInteger(100000));
			} else if (weixinQRcode.getType() == 1) {
				// 永久二维码,永久的二维码必须有一个32位的不重复的字符串为场景值ID
				weixinQRcode.setScene_str(Md5Util.md5("tongqutang2015", UUID.randomUUID().toString()));
			}
			long timestamp = System.currentTimeMillis();
			weixinQRcode.setTimestamp(timestamp);
			weixinQRcode.setCreateTime(DateFormat.dateToString(new Date(timestamp)));
			WeixinMessage message = WeixinKit.createQrcode(weixinQRcode.getType(), weixinQRcode.getScene_id(), weixinQRcode.getScene_str());
			if (EmptyUtil.isNotEmpty(message) && EmptyUtil.isNotEmpty(message.getTicket())) {
				weixinQRcode.setTicket(message.getTicket());
				weixinQRcode.setExpire_seconds(message.getExpire_seconds());
				weixinQRcode.setUrl(message.getUrl());
				weixinQRcodeDao.add(weixinQRcode);
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/** 随机生成一个大于min值的正整数 */
	private int buildRandomInteger(int min) {
		Random random = new Random();
		int value = 0;
		while (true) {
			value = random.nextInt();
			if (value > min) {
				return value;
			}
		}
	}

	@Override
	public AjaxObj deletes(String ids) throws Exception {
		if (EmptyUtil.isEmpty(ids)) {
			return new AjaxObj(0, "请选择您要删除的二维码!");
		}
		weixinQRcodeDao.deletes(ids);
		return new AjaxObj(1, "二维码删除成功!");
	}

}
